﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PQ.Model;
using PQ.IBL;
using System.Threading;
using SideBar;
using System.IO;
using PQ.Enum;
using PQ.Common;
using System.Text.RegularExpressions;
using System.Json;

namespace PQ
{
    public partial class FrmMain : Form
    {

        private IBLUser blUser;
        private UserEntity userEntity;
        private Random random = new Random();

        /// <summary>
        /// 消息 ID 号 xxxx0001 ~ xxxx0002
        /// </summary>
        private int  message_id;

        /// <summary>
        /// 日志
        /// </summary>
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(FrmMain));

        /// <summary>
        /// 收到好友 消息事件
        /// </summary>
        public event Action<MessageModel> OnFriendMessageEvent;
        
        public FrmMain()
        {
            InitializeComponent();
          
        }
        public FrmMain(IBLUser blUser, UserEntity userEntity)
        {
            string s= (random.NextDouble()*23570009).ToString().Substring(0,4);
            message_id = Convert.ToInt32((s+"0001"));
            InitializeComponent();
            this.blUser = blUser;
            this.userEntity = userEntity;
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            blUser.LogOut(this.userEntity);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.Text = "PQ";
            this.OnFriendMessageEvent += new Action<MessageModel>(FrmMain_OnFriendMessageEvent);
            //ThreadPool.QueueUserWorkItem(new WaitCallback());
            tvPQ.ImageList = new ImageList();
            tvPQ.ImageList.Images.Add("loading", PQ.Properties.Resources.loading);
            ThreadPool.QueueUserWorkItem(new WaitCallback(GetUserFriends));
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc),userEntity);
        }

        //给好友发送消息
        /// <summary>
        /// 给好友发送消息
        /// r=%7B%22to%22%3A1457967659%2C%22face%22%3A534%2C%22
        /// content%22%3A%22%5B%5C%22dddddddd2%5C%22%2C%5C%22%5C%5Cn%E3%80%90%E6%8F%90%E7%A4%BA%EF%BC%9A%E6%AD%A4%E7%94%A8%E6%88%B7%E6%AD%A3%E5%9C%A8%E4%BD%BF%E7%94%A8WebQQ%EF%BC%9Ahttp%3A%2F%2Fwebqq.qq.com%2F%E3%80%91%5C%22%2C%5B%5C%22
        /// font%5C%22%2C%7B%5C%22
        /// name%5C%22%3A%5C%22%E5%AE%8B%E4%BD%93%5C%22%2C%5C%22size%5C%22%3A%5C%2210%5C%22%2C%5C%22style%5C%22%3A%5B0%2C0%2C0%5D%2C%5C%22color%5C%22%3A%5C%22000000%5C%22%7D%5D%5D%22%2C%22
        /// msg_id%22%3A76500001%2C%22
        /// clientid%22%3A%2243650231%22%2C%22
        /// psessionid%22%3A%228368046764001e636f6e6e7365727665725f77656271714031302e3133332e34312e3230320000726900000545036e04003fbb40596d0000000a4062794778634f5366626d00000028ddce1017bdc9153867aaa41c09bc416d78be250533431cfd97fcb6ebf5c89c0d4ede599b0d2cbd69%22%7D&
        /// clientid=43650231
        /// &psessionid=8368046764001e636f6e6e7365727665725f77656271714031302e3133332e34312e3230320000726900000545036e04003fbb40596d0000000a4062794778634f5366626d00000028ddce1017bdc9153867aaa41c09bc416d78be250533431cfd97fcb6ebf5c89c0d4ede599b0d2cbd69
        /// r={"to":1457967659,
        /// "face":534,
        /// "content":"[\"dddddddd2\",\"\\n【提示：此用户正在使用WebQQ：http://webqq.qq.com/】\",[\"font\",{\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]",
        /// "msg_id":76500001,
        /// "clientid":"43650231",
        /// "psessionid":"8368046764001e636f6e6e7365727665725f77656271714031302e3133332e34312e3230320000726900000545036e04003fbb40596d0000000a4062794778634f5366626d00000028ddce1017bdc9153867aaa41c09bc416d78be250533431cfd97fcb6ebf5c89c0d4ede599b0d2cbd69"}
        /// &clientid=43650231
        /// &psessionid=8368046764001e636f6e6e7365727665725f77656271714031302e3133332e34312e3230320000726900000545036e04003fbb40596d0000000a4062794778634f5366626d00000028ddce1017bdc9153867aaa41c09bc416d78be250533431cfd97fcb6ebf5c89c0d4ede599b0d2cbd69
        /// </summary>
        void FrmMain_OnFriendMessageEvent(MessageModel obj)
        {
            //{0}  统一为 "
            //{1} 为 \"
            //{3} 为{
            //{4}为 }
            string content = string.Format(
                "[{1}{4}{1},{5},{1}{6}{1},"+
                "[{1}font{1},{2}{1}name{1}:{1}宋体{1},{1}size{1}:{1}10{1},{1}style{1}:[0,0,0],{1}color{1}:{1}000000{1}{3}]]"
                , "\"", "\\\"", "{", "}",
                "正在{}挂{}QQ 中。\"," + "[\"face\",57]," + "\"。别打扰.." + random.NextDouble() + "|" + obj.From_uin
                ,"[\"face\",14],[\"face\",5],[\"face\",13],[\"face\",96],[\"face\",74],[\"face\",73],[\"face\",2],[\"face\",55],[\"face\",57],[\"face\",101],[\"face\",96],[\"face\",10],[\"face\",88],[\"face\",42],[\"face\",71]",
                "");
            //JsonValue jv = JsonValue.Parse(obj.Content);
            //string s= jv.ToString();
             Regex re = new Regex("\\\\\u0022{1,}");
            content = re.Replace(content, "\"");
            content= content.Replace("\"", "\\\"");
            string postData = string.Format(
                "{0}to{0}:{1},{0}face{0}:{2},{0}content{0}:{0}{3}{0}," +
                "{0}msg_id{0}:{4},{0}clientid{0}:{0}{5}{0},{0}psessionid{0}:{0}{6}{0}"
                , "\"", obj.From_uin, "534", content, (message_id++),
                userEntity.ClientId, userEntity.Psessionid);
            postData = "{" + postData+"}";
            logger.Debug("要发送的数据:"+postData);
            IDictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("r", Helpers.StrConvUrlEncoding(postData, "utf-8"));
            dictionary.Add("clientid", userEntity.ClientId);
            dictionary.Add("psessionid", userEntity.Psessionid);
            PostData pd = new PostData(dictionary);
            obj.Content = pd.ToString();
            bool b = blUser.SendFriendMessage(obj, userEntity);
            if (!b)
            {
                this.SetText("发送消息失败了额." + obj.Send_uin);
            }
        }

        /// <summary>
        /// 线程池子程序
        /// </summary>
        /// <param name="stateInfo"></param>
        void ThreadProc(Object userEntity)
        {
            UserEntity user = userEntity as UserEntity;
            while (true)
            {
                List<MessageModel> messageList = blUser.GetMessage(user);
                foreach (MessageModel item in messageList)
                {
                    switch (item.MessageType)
                    {
                        case MessageTypeEnum.Message:
                            SetText(item.From_uin + "\t" + item.Content + "\tsource:"+item.Value);
                            InitFriendMessageEvent(item);
                            break;
                        case MessageTypeEnum.System_message:
                            break;
                        case MessageTypeEnum.Group_message:
                            SetText(item.Group_code + "\t" + item.Send_uin + "\t" + item.Content + "\tsource:" + item.Value);
                            break;
                        case MessageTypeEnum.Buddies_status_change:
                            SetText(item.Uin + "\t" + item.Status + "\t" + item.Client_type + "\tsource:" + item.Value);
                            break;
                        case MessageTypeEnum.NotMessage:
                            SetText("MessageTypeEnum.NotMessage:" + item.Value);
                            break;
                        case MessageTypeEnum.ErrorMessage:
                            SetText("MessageTypeEnum.ErrorMessage:" + item.Value);
                            break;
                        default:
                            SetText(item.Value);
                            break;
                    }
                }
            }
        }


        //给值
        /// <summary>
        ///  给值
        /// </summary>
        /// <param name="text"></param>
        private void SetText(string text)
        {
            if (this.rtbResult.InvokeRequired)
            {
                Action<string> action = new Action<string>(SetText);
                this.Invoke(action, text);
            }
            else
            {
                string s = string.Format("{0}. {1}{2}", DateTime.Now, text,
                    Environment.NewLine);
                this.rtbResult.AppendText(s);
                logger.Debug(s);
                this.rtbResult.ScrollToCaret();
            }
        }

        //获取好友及好友分组
        /// <summary>
        /// 获取好友及好友分组
        /// </summary>
        /// <returns></returns>
        private void GetUserFriends(object obj)
        {
            //tvPQ
            blUser.GetUserFriends(this.userEntity);
            FillTreeView(this.userEntity.Categories);
            //FillSideBarGroup(this.userEntity.Categories);
        }

            //FilllbBox();
            //FillTreeView();
            ////模拟SelectedIndexChanged事件
            //lbBox.SelectedIndex = 0;
            //lbBox.SelectedIndex = 1;
            //lbBox.SelectedIndex = 0;
 

        #region 树控件，添加信息
        /// <summary>
        /// 树控件，添加信息
        /// </summary>
        private void FillTreeView(Dictionary<int,string> dic)
        {
            foreach (KeyValuePair<int, string> kvp in dic)
            {
                TreeNode tn = new TreeNode();
                tn.Text = kvp.Value;
                tn.Tag = kvp.Key;
                //tvPQ.Nodes.Add(tn);
                SetTreeNodes(tn);
            }
            AddChildNode();

            //tvPQ.CheckBoxes = true;
           // tvPQ.ImageList = ilImage;
            //vPQ.ImageIndex = 0;
            //tvPQ.SelectedImageIndex = 1;
            //tvPQ.ExpandAll();
        }
        #endregion

        

        #region 树控件添加子结点，递归
        /// <summary>
        /// 树控件添加子结点，递归
        /// </summary>
        public void AddChildNode()
        {

            for (int i = 0; i < tvPQ.Nodes.Count; i++)
            {
                TreeNode tn = tvPQ.Nodes[i];
                int categoriesId = Convert.ToInt32(tn.Tag);
                foreach (KeyValuePair<string, FriendModel> kvp in this.userEntity.FriendsDic.
                    Where(m => m.Value.CategoriesId == categoriesId))
                {
                    TreeNode tnChild = new TreeNode();
                    
                    tnChild.Text = kvp.Value.Nick+"("+(kvp.Value.Uin)+")";
                    tnChild.Tag = kvp.Key;
                    //tn.Nodes.Add(tnChild);
                    
                    SetTreeNodes2(tnChild, tn);
                }
            }
        }
        #endregion

        //节点 展开后事件
        private void tvPQ_AfterExpand(object sender, TreeViewEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(GetUserAvatar),e);
            
        }

        //获取 用户图像
        private void GetUserAvatar(object e)
        {
            TreeNode tn= (e as TreeViewEventArgs).Node;
            int categoriesId = -1;
            if (tn!=null)
            {
                categoriesId = Convert.ToInt32(tn.Tag);
            }
            if (categoriesId<=-1)
            {
                return;
            }
            foreach (KeyValuePair<string, FriendModel> kvp in this.userEntity.FriendsDic.
                    Where(m => m.Value.CategoriesId == categoriesId))
            {
                GetUserAvatar(kvp.Key,tn);
            }
        }

        private void GetUserAvatar(string key,TreeNode tn)
        {
            if (this.tvPQ.InvokeRequired)
            {
                Action<string, TreeNode> getUa = new Action<string, TreeNode>(GetUserAvatar);
                this.Invoke(getUa, key,tn);
            }
            else
            {
                if (!tvPQ.ImageList.Images.ContainsKey(key))
                {
                    tvPQ.ImageList.Images.Add(key,Image.FromStream(blUser.GetUserAvatar(key)));
                    tn.Nodes[key].ImageKey = key;
                    tn.Nodes[key].SelectedImageKey = key;
                }
            }
            
        }


        /// <summary>
        /// 触发收到好友消息事件
        /// </summary>
        /// <param name="jsObject"></param>
        private void InitFriendMessageEvent(MessageModel mesageModel)
        {
            if (mesageModel != null)
            {
                if (OnFriendMessageEvent != null)
                {
                    OnFriendMessageEvent(mesageModel);
                }
            }
        }


        //添加 到 Nodes
        /// <summary>
        ///   添加 到 Nodes
        /// </summary>
        /// <param name="treeNode"></param>
        private void SetTreeNodes(TreeNode treeNode)
        {
            if (this.tvPQ.InvokeRequired)
            {
                Action<TreeNode> action = new Action<TreeNode>(SetTreeNodes);
                this.Invoke(action, treeNode);
            }
            else
            {
                tvPQ.Nodes.Add(treeNode);
            }
        }

        //添加 到 Nodes
        /// <summary>
        ///   添加 到 Nodes
        /// </summary>
        /// <param name="treeNode"></param>
        private void SetTreeNodes2(TreeNode sourceTreeNode, TreeNode targetTreeNode)
        {
            if (this.tvPQ.InvokeRequired)
            {
                Action<TreeNode, TreeNode> action = new Action<TreeNode, TreeNode>(SetTreeNodes2);
                this.Invoke(action, sourceTreeNode, targetTreeNode);
            }
            else
            {
                sourceTreeNode.ImageKey = "loading";
                //targetTreeNode.Nodes.Add(sourceTreeNode);
                var key =sourceTreeNode.Tag.ToString();
               TreeNode tn= targetTreeNode.Nodes.Add(key, sourceTreeNode.Text);
               
            }
        }
 

        

        //#region 加截 列表控件
        ///// <summary>
        ///// 加截 列表控件
        ///// </summary>
        //private void FillSideBarGroup(Dictionary<int,string> dic)
        //{
        //    foreach (KeyValuePair<int, string> kvp in dic)
        //    {
        //        SbGroup sbGroup = new SbGroup();
        //        sbGroup.Tag = kvp.Key;
        //        sbGroup.Text = kvp.Value;
        //        sbBars.AddGroup(sbGroup);
        //    }
        //    AddChildSBarItems();
        //}
        //#endregion

        //#region 加载 列表控件子项
        ///// <summary>
        /////  列表控件子项
        ///// </summary>
        ///// <param name="sb"></param>
        //public void AddChildSBarItems()
        //{

        //    for (int i = 0; i < sbBars.Groups.Count; i++)
        //    {
        //        SbGroup sbGroup= sbBars.Groups[i];
        //        int categoriesId = Convert.ToInt32(sbGroup.Tag);
        //        foreach (KeyValuePair<string, FriendModel> kvp in this.userEntity.FriendsDic.
        //            Where(m => m.Value.CategoriesId == categoriesId))
        //        {
        //            SbItem sbItem = new SbItem();
        //            sbItem.ImageIndex = 0;
        //            sbItem.Tag = kvp.Key;
        //            sbItem.Text = kvp.Value.Uin;
        //            sbGroup.Items.Add(sbItem);
        //        }
        //    }
           
        //    //int k = ilSideBarImage.Images.Count - 1;
        //    //for (int i = 0; i < userEntity.FriendsDic; i++)
        //    //{
        //    //    if (listSideBar[i].ParentID == Convert.ToInt32(sb.Tag))
        //    //    {
        //    //        SbItem sbItem = new SbItem();
        //    //        sbItem.Text = listSideBar[i].PurviewName;
        //    //        sbItem.Tag = listSideBar[i].PurviewID;
        //    //        //sbItem.ImageIndex = rd.Next(k);
        //    //        sb.Items.Add(sbItem);
        //    //    }
        //    //}
        //}
        //#endregion







    }
}
